import { SocketServer } from "@/App";
import { IStore } from "@/store";
import { Alert, Button, Result, Spin, message } from "antd";
import { memo, useEffect, useState } from "react";
import { shallowEqual, useSelector } from "react-redux";
import { useLocation, useNavigate, useNavigation } from "react-router-dom";
const NotFound = memo(() => {
  const navgiate = useNavigate();
  const _ = useLocation();
  const store = useSelector((state: IStore) => state.user, shallowEqual);
  const [flag, setFlag] = useState(false);
  function GoBackHomeClick() {
    SocketServer?.close();
    navgiate("/login");
  }
  useEffect(() => {
    console.log("=> 进来了  ")
    let flag = false;
    let per = false;
    let timer: any = null;
    let arr: any[] = [];
    // 是否有菜单
    if (store.menu.length > 0) {
      store.menu.forEach((item) => {
        item.children?.forEach((itemy: any) => {
          // 保存所有的子菜单
          arr.push(itemy);
          // 是否有当前路由的菜单！
          itemy.key === _.pathname && (flag = true);
        });
      });
    }
    const item = arr.find((item) => {
      return item.key == _.pathname;
    });
    if (flag) {
      clearTimeout(timer);
      timer = null;
      if (!item) {
        setFlag(true);
        return;
      }
    } else {
      timer = setTimeout(() => {
        const user = localStorage.getItem("user");
        const token = localStorage.getItem("token");
        if (user && token) {
          if (!item && store.menu.length) {
            setFlag(true);
            return;
          }
          navgiate(_.pathname);
          return;
        }
        message.error("请重新登陆！！");
        setFlag(true);
      }, 1000);
    }
    return () => {
      clearTimeout(timer);
      timer = null;
    };
  }, [store.menu]);
  return (
    <div className="overflow-y-auto">
      <div className="notfound">
        {flag ? (
          <div className="h-full flex justify-around items-center flex-col">
            <h1 className="text-2xl">404</h1>
            <Button onClick={() => GoBackHomeClick()} type="primary">
              返回登陆
            </Button>
          </div>
        ) : (
          <div className="load-data">
            <Spin className="mt-80" tip="Loading...">
              <Alert
                message="请求数据中..."
                description="根据您网络的速度..."
                type="info"
              />
            </Spin>
          </div>
        )}
      </div>
    </div>
  );
});

export default NotFound;
